package com.pipayshop.utils;

//import com.esotericsoftware.minlog.Log;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;

/**
 * @author wzx
 */
public class TokenUtil {
  private static  SecretKey key = Keys.hmacShaKeyFor(Constants.TOKEN_SECRET.getBytes(StandardCharsets.UTF_8));

    /**
     * 获取token，将传递的数据封装进JWT的荷载中
     */
    public static String getToken(String piName){
        if (piName == null){return null;}
        JwtBuilder jwtBuilder = Jwts.builder();

        return jwtBuilder
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .claim("pi_name", piName)
                .setExpiration(new Date(System.currentTimeMillis() + Constants.USER_ACTIVE_TIME))
                .signWith(key)
                .compact();
    }

    /**
     * 获取token，将传递的数据封装进JWT的荷载中
     */
    public static String getTradinOrderToken(String orderId, String userId) throws IllegalArgumentException {
        if (orderId == null || userId == null) {
            throw new IllegalArgumentException("订单号和用户ID不能为空");
        }
        JwtBuilder jwtBuilder = Jwts.builder();
        return jwtBuilder
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .claim("orderId", orderId)
                .claim("userId", userId)
                .setExpiration(new Date(System.currentTimeMillis() + Constants.USER_ACTIVE_TIME))
                .signWith(key)
                .compact();
    }

    /**
     * 解密Token，拿到内部封装的userId数据
     */
//    public static Claims getDataFromToken(String token){
//        JwtParserBuilder builder = Jwts.parserBuilder();
//        JwtParser jwtParser = builder.build();
//        // 通过签名对Token进行解析，得到的结果是一个类似集合的封装类
////        Jws<Claims> claimsJws = jwtParser.setSigningKey(Constants.TOKEN_SECRET.getBytes(StandardCharsets.UTF_8)).parseClaimsJws(token);
////        Key key = Keys.hmacShaKeyFor(Constants.TOKEN_SECRET.getBytes(StandardCharsets.UTF_8));
////        System.out.println(key);
//
//        Jws<Claims> claimsJws = Jwts.parserBuilder()
//                .setSigningKey(Constants.TOKEN_SECRET.getBytes(StandardCharsets.UTF_8))
//                .build()
//                .parseClaimsJws(token);
//        return claimsJws.getBody();
//    }
    public static Claims getDataFromToken(String token) {
        SecretKey key = Keys.hmacShaKeyFor(Constants.TOKEN_SECRET.getBytes(StandardCharsets.UTF_8));
        JwtParser jwtParser = Jwts.parserBuilder()
                .setSigningKey(key)
                .build();

        try {
            Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
            return claimsJws.getBody();
        } catch (Exception e) {
            System.err.println("Token解析失败: " + e.getMessage());
            throw new RuntimeException("Token解析失败");
        }
    }

    /**
     * 解密Token，拿到内部封装的userId数据，不同字节数组进行匹配
     */
    public static Claims getDataFromToken2(String token){
        JwtParser jwtParser = Jwts.parser();
        // 通过签名对Token进行解析，得到的结果是一个类似集合的封装类
        Jws<Claims> claimsJws = jwtParser.setSigningKey(Constants.TOKEN_SECRET).parseClaimsJws(token);
        return claimsJws.getBody();
    }
    private static SecretKey generateSecureSecretKey() {
        // 使用 Keys 类生成 256 位密钥
        return Keys.secretKeyFor(io.jsonwebtoken.SignatureAlgorithm.HS256);
    }

}
